<?php
namespace app\index\controller;

use think\Db;
use think\facade\Session;
use app\common\traits\Provide;

class Service extends Base
{
    use Provide;

    public function index()
    {
        $room_id = (int)input('room_id');
        if(!$room_id)
        {
            $this->assign('msg','请输入房间号!');
            return $this->fetch('public/error');
        }
        if(!Session::get('service_info'))
        {
            $this->redirect('service/serviceLogin?room_id='.$room_id);
        }

        $service_info = Session::get('service_info');
        $this->assign('service_info', $service_info);
        return $this->fetch('service/service_index');
    }

    /*
     * 打开客服
     */
    public function openService()
    {
        $user_token = input('token');
        $service_id  = input('service_id');
        $service_name = input('service_name');
        $service_avatar = input('service_avatar');
        //打开客服人的信息
        $user_info = $this->getUserInfoByToken($user_token);
        $user_info['user_token'] = $user_token;
        $user_info['service_id'] = $service_id;
        $user_info['service_name'] = $service_name;
        $user_info['service_avatar'] = $service_avatar;

        $this->assign('open_data', $user_info);
        return $this->fetch('service/open_service');
    }

    /*
     * 客服登录
     */
    public function serviceLogin()
    {
        $room_id = input('room_id');
        if(\request()->isAjax())
        {
            $where['phone|name'] = input('name');
            $where['role'] = '6';  //6 为客服
            $password = input('password');
            $service_info = Db::name('user')->where($where)->find();
            if($service_info && password_verify($password, $service_info['password']))
            {
                $user_info['service_id']   = $service_info['id'];
                $user_info['user_id']   = $service_info['id'];
                $user_info['service_name'] = $service_info['name'];
                $user_info['service_avatar']    = $service_info['avatar'];
                $user_info['room_id']   = $room_id;
                $user_info['token']     = $this->getToken($user_info);
                session('service_info', $user_info);
                return responseJson(200,'登录成功');
            }else{
                return responseJson(400,'用户名或者密码错误');
            }
        }else{
            $this->assign('room_id', $room_id);
            return $this->fetch('service/service_login');
        }
    }

}